﻿/*
 * Created by SharpDevelop.
 * User: Hellen(LongFan)
 * Date: 2015/12/26
 * Time: 13:39
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Text;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Comm
{
	/// <summary>
	/// Description of SendDataForm.
	/// </summary>

	public delegate void MySendDataFromEventHandle(object sender, SendDataEventArgs e);
	public delegate void MySendDataFromClosedEventHandle(object sender, EventArgs e);		
	//My send data event
	public class SendDataEventArgs : EventArgs
	{
		public readonly string SendString;
		public SendDataEventArgs(string s)
		{
			SendString = s ;
		}
	}
	
	public partial class SendDataForm : Form
	{		
		public event MySendDataFromEventHandle MySendDataEvent;
		public event MySendDataFromClosedEventHandle MySendFromClosedEvent;
		
		public static bool RunSendThread = true;
		public static bool AutoSendStatus = false ;		//the auto send status
		public static long IntervalTime = 0 ;			//
		private long SendTime = 0;						//the send time(baud)
		
		public SendDataForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
			SendTime = ( 1000000000/MyCommClass.SBaudRate ) * 10 ;		//takes time when send a frame (ns)
		}
		
		void SendDataButtonClick(object sender, EventArgs e)
		{		
			string[] HexStrArray = new string[SendDataComboBox.Text.Length/2 + 2 ];
			StringBuilder sb = new StringBuilder();
			
			AutoSendStatus = AutoCheckBox.Checked;
			SendDataEventArgs MySendDataEvnetArgs;
			
			if( SendDataComboBox.Text != "")
			{//if no string, no send operation
				if( HEXRadioButton.Checked )
				{//HEX model spilt string
					HexStrArray = SendDataComboBox.Text.Split(new char[]{' '});
					foreach(string s in HexStrArray)
					{
						if( s != "" )
						{	//if is not a "", turn it to byte
							//HexStrBytes.Add( (char)Convert.ToInt32( s, 16 ) );
							sb.Append( Convert.ToChar(byte.Parse(s, NumberStyles.AllowHexSpecifier)) );
						}
					}
					MySendDataEvnetArgs = new SendDataEventArgs( sb.ToString());
				}
				else
				{
					MySendDataEvnetArgs = new SendDataEventArgs(SendDataComboBox.Text);
				}
				if( MyCommClass.Opened )
				{//check the comm must be opened
					if(MySendDataEvent != null)
					{//if the event have handle function
						MySendDataEvent(this, MySendDataEvnetArgs);
					}
				}
				else
				{
					MessageBox.Show("No Communicata Port Opened\n" +
					                "无打开串口，请先设置端口！");
				}
			}
			//updata the button show
			if(SendDataButton.Text == "发送")
			{
				if(AutoSendStatus)
				{	//start the Auto Send thread
					RunSendThread = true;
					//updata the button show
					SendDataButton.Text = "停止发送" ;
					SendDataComboBox.Enabled = false;
				}
			}
			else
			{	//Stop the auto send thread
				RunSendThread = false;
				//updata the button
				SendDataButton.Text = "发送" ;
				AutoSendStatus = false;
				AutoCheckBox.Checked = false;
				SendDataComboBox.Enabled = true;
			}
			//check if save the send history
			if(SendHistoryCheckBox.Checked)
			{
				foreach(object item in SendDataComboBox.Items)
				{
					if( item.ToString() == SendDataComboBox.Text )
					{//Have the history
						return ;
					}
				}
				if( SendDataComboBox.Items.Count < 101 )
				{//save 100 historys
					SendDataComboBox.Items.Insert(0, SendDataComboBox.Text.ToString());
				}
			}
		}
		
		void SendDataFormFormClosed(object sender, EventArgs e)
		{
			RunSendThread = false;			//stop the thread
			MySendFromClosedEvent(this, e);	//send event
		}
		
		void TimetextBoxTextChanged(object sender, EventArgs e)
		{
			try
			{
				IntervalTime = long.Parse(TimetextBox.Text) ;
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
			switch(TimeComboBox.SelectedIndex)
			{
				case 0:				//us
					IntervalTime = IntervalTime * 1000 ;		//turn to ns
					if( 1000000 < IntervalTime )
					{	//if time is biger then 1000ms
						MessageBox.Show("Please use \"us\" or \"s\" ");
						return ;
					}
					break ;
				case 1:				//ms
					IntervalTime = IntervalTime * 1000 * 1000 ;
					if( 1000000000000 < IntervalTime )
					{	//if time is biger then 1000s
						MessageBox.Show("Please use \"s\" ");
						return ;
					}
					break ;					
				case 2:				//s
					IntervalTime = IntervalTime * 1000 * 1000 *1000 ;
					if( 3600000000000 < IntervalTime )
					{
						MessageBox.Show("You set time > 1 hour! \n" +
						                "The maxim time is 106751 days! Don`t biger this!!");
					}
					break ;
			}
			if( IntervalTime < SendTime )
			{	//if the interval time < send time, set the interval tiem default value
				MessageBox.Show("The Interval Time < Send Dat Time, Please Reset The Interval Time. \n" +
				                "The Send Data Time is " +
				                ((float)SendTime/1000000).ToString() + "ms" );
				TimetextBox.Text = "500" ;
				IntervalTime = 500000000 ;
				TimeComboBox.SelectedIndex = 1 ;
				return ;
			}
		}
		
		void TimeComboBoxSelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				IntervalTime = long.Parse(TimetextBox.Text) ;
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}			
			switch(TimeComboBox.SelectedIndex)
			{
				case 0:				//us
					IntervalTime = IntervalTime * 1000 ;		//turn to ns
					if( 1000000 < IntervalTime )
					{	//if time is biger then 1000ms
						MessageBox.Show("Please use \"us\" or \"s\" ");
						return ;
					}
					break ;
				case 1:				//ms
					IntervalTime = IntervalTime * 1000 * 1000 ;
					if( 1000000000000 < IntervalTime )
					{	//if time is biger then 1000s
						MessageBox.Show("Please use \"s\" ");
						return ;
					}
					break ;					
				case 2:				//s
					IntervalTime = IntervalTime * 1000 * 1000 *1000 ;
					if( 3600000000000 < IntervalTime )
					{
						MessageBox.Show("You set time > 1 hour! \nThe maxim time is 106751 days! Don`t biger this!!");
					}
					break ;
			}	
			if( IntervalTime < SendTime )
			{
				MessageBox.Show("The Interval Time < Send Dat Time, Please Reset The Interval Time. \n" +
				                "The Send Data Time is " +
				                SendTime.ToString() + "ms" );
				TimetextBox.Text = "500" ;
				IntervalTime = 500000000 ;
				TimeComboBox.SelectedIndex = 1 ;
				return ;
			}			
		}
		
		void SendDataComboBoxKeyPress(object sender, KeyPressEventArgs e)
		{
			string pattern = @"^[0-9A-Fa-f\s,\.]$";

			if( HEXRadioButton.Checked && 21 < Convert.ToInt32(e.KeyChar))
			{//HEX Input Mode, check the inputs
				if( !Regex.IsMatch(e.KeyChar.ToString(), pattern) )
				{//it is not a hex char, do nothing
					MessageBox.Show("You input must in [0-9],[A-Z],[a-z],[ ],[,],[,]");
					//Give up the input
					e.Handled = true;
					return ;
				}
				if( Regex.IsMatch(e.KeyChar.ToString(), @"^[\s,\.]$") )
				{//if a "," "." ro " " split use " "
					//SendDataComboBox.Text = SendDataComboBox.Text.ToString() + " ";
					//e.Handled = true;
					//SendKeys.Send("{BS}");
					e.KeyChar = (char)Keys.Space;
				}
			}			
		}
		
		void SendDataComboBoxSelectedIndexChanged(object sender, EventArgs e)
		{
			if( SendDataComboBox.SelectedItem.ToString().Equals("......清空历史") )
			{
				SendDataComboBox.Items.Clear();
				SendDataComboBox.Items.Add("......清空历史");
			}
		}
		
		void StringRadioButtonCheckedChanged(object sender, EventArgs e)
		{
			SendDataComboBox.Text = "";
		}
		
		void HEXRadioButtonCheckedChanged(object sender, EventArgs e)
		{
			//clear the text
			SendDataComboBox.Text = "";
			//if hex model, enable generate verity
			if(HEXRadioButton.Checked)
			{
				VerityButton.Enabled = true;
				VerityTextBox.Enabled = true;
			}
			else
			{
				VerityButton.Enabled = false ;
				VerityTextBox.Enabled = false ;
			}
		}
		
		void VerityButtonClick(object sender, EventArgs e)
		{
			byte Verity = 0;
			if( SendDataComboBox.Text != "" )
			{//if have text, can generate verity char
				foreach(string s in SendDataComboBox.Text.Split(new char[]{' '}))
				{
					if( s != "" )
					{
						try
						{
							Verity ^= byte.Parse(s, NumberStyles.HexNumber);
						}
						catch(Exception ex)
						{
							MessageBox.Show(ex.ToString());
						}
					}
				}
				//show the verity and add the verity to the tail of the text
				VerityTextBox.Text = String.Format("{0:X}",Verity);
				if( VerityTextBox.Text != "0" )
				{
					SendDataComboBox.Text +=  (" " + VerityTextBox.Text);
				}
			}
		}
	}
}
